package com.jfcloud.common.utils;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;



public class AESUtil{
    
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//Ĭ�ϵļ����㷨
    
    public static String encrypt(String content, String key) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// ����������
    
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
    
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// ��ʼ��Ϊ����ģʽ��������
    
            byte[] result = cipher.doFinal(byteContent);// ����
            
            return new String( Base64.getEncoder().encode(result), StandardCharsets.UTF_8);//ͨ��Base64ת�뷵��
            
        } catch (Exception ex) {
            Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    
        return null;
    }
    
    public static String decrypt(String content, String key) {
    
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
    
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
    
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
            
    
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    
        return null;
    }
    
    /**
     * ���ɼ�����Կ
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) {
        KeyGenerator kg = null;
    
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
    
            kg.init(128, new SecureRandom(key.getBytes()));
    
            SecretKey secretKey = kg.generateKey();
    
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// ת��ΪAESר����Կ
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    
        return null;
    }
    
    public static void main(String[] args) {
        String content = "hello";
        String key = "sde@5f98H*^hsff%dfs$r344&df8543*er";
        System.out.println("content:" + content);
        String s1 = AESUtil.encrypt(content, key);
        System.out.println("s1:" + s1);
        System.out.println("s2:"+AESUtil.decrypt(s1, key));
    
    }
    
}